﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Text;

namespace TheVerge.Phone.Imp
{
    public static class PhoneImageSaver
    {

        private class RequestState
        {
            public Uri OriginalUri { get; set; }
            public Action<Uri> OnFinished { get; set; }
            public Action<Exception> OnError { get; set; }
        }

        public static void Save(Uri uri, Action<Uri> OnFinished, Action<Exception> OnError)
        {
            var webClient = new WebClient();
            webClient.OpenReadCompleted += WebClient_OpenReadCompleted;
            var state = new RequestState { OriginalUri = uri, OnFinished = OnFinished, OnError = OnError };
            webClient.OpenReadAsync(uri, state);
        }

        private static void WebClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            var state = e.UserState as RequestState;
            try
            {
                var fileName = GetFileName(state.OriginalUri);

                using (var isoFile = IsolatedStorageFile.GetUserStoreForApplication())
                using (var isoStream = new IsolatedStorageFileStream(fileName, FileMode.Create, isoFile))
                {
                    var stream = e.Result;

                    stream.CopyTo(isoStream);

                    stream.Close();
                    isoStream.Close();
                }

                var returnUri = new Uri(string.Format(@"isostore:{0}", fileName), UriKind.Absolute);
                state.OnFinished(returnUri);
            }
            catch (Exception exp)
            {
                state.OnError(exp);
            }
        }

        private static string GetFileName(Uri originalUri)
        {
            return string.Format(@"/Shared/ShellContent/{0}.png", originalUri.ToString().GetHashCode());
        }
    }
}
